package com.github.gaojh.ioc.bean;

import cn.hutool.core.convert.Convert;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author gaojh
 * @since 2020/3/21
 */
public class FlyingIoc implements Ioc {

    private final static ConcurrentHashMap<String, Object> BEAN_MAP = new ConcurrentHashMap<>(128);

    @Override
    public <T> T getBean(Class<T> clazz) {
        String name = clazz.getName();
        Object object = BEAN_MAP.get(name);
        if (object != null) {
            return clazz.cast(object);
        }
        return null;
    }

    @Override
    public Object getBean(String name) {
        return BEAN_MAP.get(name);
    }

    @Override
    public void addBean(Object object) {
        String name = object.getClass().getName();
        BEAN_MAP.put(name, object);
    }

    @Override
    public void addBean(String name, Object object) {
        BEAN_MAP.put(name, object);
    }

    @Override
    public boolean containsBean(String name) {
        return BEAN_MAP.containsKey(name);
    }

    @Override
    public <T> List<T> getBeansByInterface(Class<T> tClass) {
        return BEAN_MAP.values().stream().filter(o -> tClass.isAssignableFrom(o.getClass())).map(o -> Convert.convert(tClass, o)).collect(Collectors.toList());
    }

    @Override
    public <T> List<T> getBeansByType(Class<T> tClass) {
        return BEAN_MAP.values().stream().filter(o -> o.getClass().equals(tClass)).map(o -> Convert.convert(tClass, o)).collect(Collectors.toList());
    }

    @Override
    public  List<Object> getAllBeans() {
        return new ArrayList<>(BEAN_MAP.values());
    }

}
